package SwingUiChatting;

import chattingRoom.ReleaseUtils;

import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.Scanner;

/**
 * 客户端的发送方法
 */
public class ClientSend implements Runnable{

    private DataOutputStream dataOutputStream;
    private Socket client;
    private boolean isRunning;
    private Scanner scanner;
    private String username;
    public ClientSend(Socket client, String username){
        this.client=client;
        try {
            dataOutputStream=new DataOutputStream(client.getOutputStream());
            this.username=username;
            //当管道连接成功之后，就将用户名发送过去
            sendMessage(username);
            /**
             * 注意 就因为这个地方没写true底下的send方法根本就没跑的起来，搞了我半天
             */
            isRunning=true;
            scanner=new Scanner(System.in);
        } catch (IOException e) {
            release();
            System.out.println("客户端发送模块出现了问题");
        }
    }

    private void sendMessage(String message){
        try {
            dataOutputStream.writeUTF(message);
            dataOutputStream.flush();
        } catch (IOException e) {
            release();
            System.out.println("发送信息的过程出现了错误");
        }
    }

    private void release(){
        this.isRunning=false;
        ReleaseUtils.close(dataOutputStream,client);
    }

    @Override
    public void run() {
        while (isRunning){
            //读取控制台的输入信息
            //这里使用scanner可能你在输入台的信息之间不能有空格  你可以使用buffer Reader进行使用
            String message=scanner.next();
            if (!message.equals("")){
                sendMessage(message);
            }
        }

    }
}
